package com.demo.net;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    private static boolean running = true;
    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(System.in);
        // 1.创建到服务器的连接
        Socket socket = new Socket("127.0.0.1", 10086);
        //获取输出流 - 发送给服务器的数据
        OutputStream out = socket.getOutputStream();
        out.write("hello server i am a client\n".getBytes());
        out.flush(); // 发送
        new Thread(() -> {
            while(true){
                System.out.print("请输入内容呗:");
                String text = in.next();
                if(text.equalsIgnoreCase("exit")){
                    running = false;
                    break;
                }
                try {
                    out.write((text + "\n").getBytes() );
                    out.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        // 获取输入流 - 接收从服务器发来的数据
        // 使用缓冲区读取器读取
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line;
        while (running) {
            line = br.readLine(); // 每次读一行
            if(null == line) break; // 没有可读了
            System.out.println("服务器发来了:" + line);
        }
        in.close();
        br.close();
        out.close();
        socket.close();
    }
}
